<template>
  <el-dialog
      top="10vh"
      width="600px"
      title="添加/编辑分类"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    />

  </el-dialog>
</template>

<script>
import {http} from '@/api'

export default {
  name: 'CategoryAdd',
  data() {
    return {
      apiKey: 'category',
      dialogValue: false,
      ruleForm: {},
      defaultForm: {
        name: '',
        description: '',
        sort: 0,
        status: 1
      },
      rules: {
        name: [{required: true, message: '分类名称不能为空'}],
      },
      formList: [
        {
          label: '分类名称',
          prop: 'name',
          name: 'input',
          colSpan: 24,
          placeholder: '请输入分类名称'
        },
        {
          label: '描述',
          prop: 'description',
          name: 'input',
          colSpan: 24,
          rows: 3,
          placeholder: '请输入分类描述'
        },
        {
          label: '排序',
          prop: 'sort',
          name: 'number',
          colSpan: 12,
          min: 0
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 24,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用'
        },
      ]
    }
  },
  methods: {
    handleFormChange({key, val}) {
      // 处理表单变化
    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data
          }
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
      }
    },
    onSave() {
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, this.ruleForm).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style> 